#!/bin/sh

set -eu
if [ -z "${SIDEKICK_HOME:-}" ]; then
    case "$(cd "$(dirname "$0")" && pwd -P)" in
        */TupleStaging.app/*) SIDEKICK_HOME="$HOME/.tuplestaging/sidekick" ;;
        */TupleDev.app/*)     SIDEKICK_HOME="$HOME/.tupledev/sidekick" ;;
        *)                    SIDEKICK_HOME="$HOME/.tuple/sidekick" ;;
    esac
fi

PHASES="starting finding_call loading_wiki connecting catching_up listening wrapping_up done error"
PHASE="${1:-}"
case " $PHASES " in
    *" $PHASE "*) ;;
    *) echo "usage: sidekick-status <$(echo $PHASES | tr ' ' '|')> [detail] [--call id]" >&2; exit 2 ;;
esac
shift
DETAIL=""
CALL=""
while [ $# -gt 0 ]; do
    case "$1" in
        --call) CALL="${2:-}"; shift 2 ;;
        *) DETAIL="$1"; shift ;;
    esac
done

esc() { printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g' | tr -d '\n\r\t'; }

DIR="$SIDEKICK_HOME"
mkdir -p "$DIR"

case "$PHASE" in wrapping_up|done|error)
    if [ -n "$CALL" ] && [ -f "$DIR/status.json" ]; then
        cur_call=$(sed -n 's/.*"call":"\([^"]*\)".*/\1/p' "$DIR/status.json")
        cur_phase=$(sed -n 's/.*"phase":"\([^"]*\)".*/\1/p' "$DIR/status.json")
        if [ -n "$cur_call" ] && [ "$cur_call" != "$CALL" ]; then
            case "$cur_phase" in done|error) ;; *) exit 0 ;; esac
        fi
    fi ;;
esac

printf '{"phase":"%s","detail":"%s","call":"%s","at":%s}\n' \
    "$PHASE" "$(esc "$DETAIL")" "$(esc "$CALL")" "$(date +%s)" > "$DIR/status.json.tmp"
mv "$DIR/status.json.tmp" "$DIR/status.json"
